package com.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Administrator
 */
@Controller
@Slf4j
public class UploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpSession session) throws IOException {
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        String contentType = file.getContentType();
        log.info(contentType);
        String extension = FilenameUtils.getExtension(filename);
        String realPath = session.getServletContext().getRealPath("\\upload");
        File file1 = new File(realPath);
        if(!file1.exists()){
            file1.mkdirs();
        }
        file.transferTo(new File(realPath+File.separator+uuid+"."+extension));
        log.info("上传文件");
        return "ok";
    }


    @RequestMapping("/download")
    public void Download(String fileName, HttpSession session, HttpServletResponse response) throws IOException {
        String realPath = session.getServletContext().getRealPath("\\upload");
        String path = realPath+File.separator+fileName;
        response.setHeader("content-disposition","attachment;filename="+fileName);
        IOUtils.copy(new FileInputStream(path),response.getOutputStream());


    }
}
